package com.jackstraw.jack_base.remote_command.service.impl;

import com.jackstraw.jack_base.remote_command.config.JschConfig;
import com.jackstraw.jack_base.remote_command.entity.Conn;
import com.jackstraw.jack_base.remote_command.entity.InitVo;
import com.jackstraw.jack_base.remote_command.entity.ModelEnum;
import com.jackstraw.jack_base.remote_command.pool.entity.SessiontConnectionConfig;
import com.jackstraw.jack_base.remote_command.service.InstallService;
import com.jackstraw.jack_base.remote_command.service.JschService;
import com.jackstraw.jack_base.util.exception.BadRequestException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.stereotype.Service;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Slf4j
@Service
public class InstallServiceImpl implements InstallService {

    public static final String ROOT_USERNAME = "root";

    @Autowired
    private ResourceLoader resourceLoader;

    @Autowired
    private JschConfig jschConfig;
    @Autowired
    private JschService jschService;

    @Override
    public JschService getJschService() {
        return this.jschService;
    }

    @Override
    public Boolean checkRootUser(String connName) {
        SessiontConnectionConfig sessiontConnectionConfig = jschConfig.getSessiontConnectionConfigMap().get(connName);
        if (ObjectUtils.isEmpty(sessiontConnectionConfig)) {
            throw new BadRequestException("3100000004", "无法通过ConnName找到配置文件，请检查ConnName：【{}】是否正确", connName);
        }
        if (!ROOT_USERNAME.equals(sessiontConnectionConfig.getUserName())) {
            return Boolean.FALSE;
        }
        return Boolean.TRUE;
    }

    @Override
    public void init(InitVo initVo) throws Exception {
        Map<String, List<String>> dictConnMap = initVo.resolveEnv(this.jschConfig);
        if (ModelEnum.single.equals(initVo.getModelEnum())) {
            //说明是单机节点
            this.init(initVo.getConnName());
        } else if (ModelEnum.cluster.equals(initVo.getModelEnum())) {
            //说明是集群节点
            dictConnMap.keySet().stream().forEach(connName -> {
                try {
                    this.init(connName);
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
            });
        }
        this.envInit(initVo);
    }

    @Override
    public void envInit(InitVo initVo) throws Exception {
        Map<String, List<String>> dictConnMap = initVo.resolveEnv(this.jschConfig);
        if (ModelEnum.single.equals(initVo.getModelEnum())) {
            this.envInit(initVo.getConnName(), dictConnMap.get(initVo.getConnName()));
        } else if (ModelEnum.cluster.equals(initVo.getModelEnum())) {
            dictConnMap.keySet().stream().forEach(connNme -> {
                try {
                    this.envInit(connNme, dictConnMap.get(connNme));
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
            });
        }
    }

    @Override
    public void envInit(String connName, List<String> dictList) throws Exception {
        String rootConnName = SessiontConnectionConfig.getRootConnName(connName);
        this.getJschService().execAllShell(Conn.buildExec(rootConnName), dictList);
    }

    @Override
    public void init(String connName) throws Exception {
        String rootConnName = SessiontConnectionConfig.getRootConnName(connName);
        //1.拷贝  将init.sh拷贝到指定路径
        Resource resource = resourceLoader.getResource("classpath:install/init.sh");
        //2.获取session
        InputStream inputStream = resource.getInputStream();
        //4.执行
        log.info("init  start");
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
        List<String> cmdList = new ArrayList<>();
        String line = "";
        while ((line = bufferedReader.readLine()) != null) {
            line = line.trim();
            if (!"".equals(line) && !line.startsWith("#")) {
                cmdList.add(line);
            }
        }
        if (cmdList.size() > 0) {
            String execAllShell = this.getJschService().execAllShell(Conn.buildExec(rootConnName), cmdList);
        }
        log.info("init  end");
        resource = resourceLoader.getResource("classpath:install/settings.xml");
        inputStream = resource.getInputStream();
        //5.上传maven配置文件
        this.getJschService().upload(Conn.buildSftp(rootConnName),
                "/apps/soft/apache/maven382/conf", inputStream, "settings.xml");
        //6.赋权限
        this.getJschService().execShell(Conn.buildExec(rootConnName), "chown jack:jack -R /apps");
        //7.修改主机名
        this.getJschService().execShell(Conn.buildExec(rootConnName), "hostnamectl set-hostname ".concat(connName));
        //8.删除初始化脚本
        this.getJschService().execShell(Conn.buildExec(rootConnName), "rm -rf /apps/otherdata/init.sh");
        //9.上传脚本
        resource = resourceLoader.getResource("classpath:install/ipchange.sh");
        inputStream = resource.getInputStream();
        this.getJschService().upload(Conn.buildSftp(rootConnName), "/usr/bin/", inputStream, "ipchange");
        resource = resourceLoader.getResource("classpath:install/filecopy.sh");
        inputStream = resource.getInputStream();
        this.getJschService().upload(Conn.buildSftp(rootConnName), "/usr/bin/", inputStream, "filecopy");
        //10.赋权限
        this.getJschService().chmodInstall(Conn.buildExec(rootConnName), "/usr/bin/filecopy");
        this.getJschService().chmodInstall(Conn.buildExec(rootConnName), "/usr/bin/ipchange");
    }
}
